home *** CD-ROM | disk | FTP | other *** search
- Path: pegasus.montclair.edu!harmon
- From: harmon@pegasus.montclair.edu (Derek Harmon)
- Newsgroups: comp.lang.c
- Subject: Re: How do I round and truncate floats to integers?
- Date: 16 Feb 1996 00:38:09 -0500
- Organization: Montclair State University
- Message-ID: <harmon.824447677@pegasus.montclair.edu>
- References: <4g009b$c2n@news.tuwien.ac.at>
- NNTP-Posting-Host: pegasus.montclair.edu
- X-Newsreader: NN version 6.5.0 #68 (NOV)
-
- sor@rs6.iaee.tuwien.ac.at (Evgeni Sorokin) writes:
- >Given a float (double, to be exact) how do I
-
- >1) round it to nearest integer (forget 0.5 problem for the moment) and
- >2) truncate it to the integer?
-
- #2 first, to truncate any fractional component (it will still be of type
- double, however), use floor() on positive numbers and ceil() on negative
- numbers. They are both in the standard <math.h>. The answer for #1 involves
- adding 0.5 to the value, and then applying #2.
-
- > If typecasting is supposed to do the trick, then how do I
- >distinguish cases 1) and 2)?
-
- It is important to note that a C typecast only tells the compiler to treat
- some form of data as another form of data. No change is made to the data.
- The binary representation of a double floating point value is very different
- from that of an integer, and just telling the compiler to treat it as an int
- will not solve your problem (for example, 7 != (int)'7').
-
- unsigned int real2int( double real )
- {
- unsigned int whole = 0;
- unsigned int pow = 10000;
-
- if (real > 65535.0) {
- fputs(stderr, "real value too large in real2int().\n");
- exit( 1 );
- }
- real = floor(real);
- while ( pow > 0 )
- if (real > (pow * 1.0)) {
- real -= (pow * 1.0);
- whole += pow;
- } else pow /= 10;
-
- return( whole );
- }
-
- This little routine is more or less what you're looking for. It makes
- several assumptions in that real must be positive, less than what a 16-bit
- unsigned int can hold (the extension to a long is straightforward), but you
- should find it workable.
- -- Stone
- --
- # Derek Harmon (aka Stonelight) harmon@pegasus.montclair.edu
- # - Computer Science Undergrad, Montclair State University, NJ
- # - My views are my own, nobody else is this creative. 3;)>
- ... Sure I can program in Pascal, what's it Wirth to ya?
-